<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/12/1
 * Time: 09:02
 */

namespace Api\Controller;


use Api\Vendor\Zjport\GoodsDeclar;
use Library\Api\ZjportUploadHisApi;
use Library\Model\ZjportUploadHisModel;
use Shop\Api\OrderBillResultApi;
use Shop\Api\OrdersApi;
use Shop\Api\OrdersExpressApi;
use Shop\Api\OrderStatusApi;
use Shop\Api\OrderStatusHistoryApi;
use Shop\Api\OrderTaxNeedApi;
use Shop\Api\ZjportOrderStatusApi;
use Think\Controller\RestController;

class ZjportCallbackController extends RestController {

    public function __construct(){
        parent::__construct();

        load_ext_file(COMMON_PATH);
    }

    public function index(){

        addLog("ZjportCallback/index",$_GET,$_POST,"接收到电子口岸回调信息");
        $content = $_POST['content'];
        $content = str_replace(" ","+",$content);
        addLog("ZjportCallback/index",base64_decode($content),$content,"取出Content数据，电子口岸回调信息");

//        $content = '<mo version="1.0.0"><head><businessType>PERSONAL_GOODS_DECLAR</businessType></head><body><goodsDeclareModuleList><goodsDeclareModule><jkfSign><companyCode>341905940</companyCode><businessNo>549020151209173133</businessNo> <businessType>PERSONAL_GOODS_DECLAR</businessType> <declareType>1</declareType><note></note></jkfSign><goodsDeclare><accountBookNo></accountBookNo><inOutDateStr></inOutDateStr><warpType></warpType><netWeight></netWeight><remark></remark><declarantNo></declarantNo><paperNumber>330327199108120957</paperNumber><paperType>1</paperType><isAuthorize>1</isAuthorize><applicationFormNo>A33015600052015100000004</applicationFormNo><internalAreaCompanyName>杭州汉达国际货运代理有限公司</internalAreaCompanyName><internalAreaCompanyNo>3301560005</internalAreaCompanyNo><mainGName>美国善存Centrum成人女士复合维生素多种营养素矿物质</mainGName><currCode>142</currCode><worth>86</worth><senderCity></senderCity><senderCountry>142</senderCountry><consignee>王大锤</consignee><senderName>杭州马班科技有限公司</senderName><customsField>292801</customsField><enteringCompanyName>9999</enteringCompanyName><enteringPerson>9999</enteringPerson><declPort>7218</declPort><grossWeight>0.4</grossWeight><packNo>1</packNo><tradeCountry>100</tradeCountry><wayBill>1063163730100</wayBill><orderNo>153421523553644319S</orderNo><eCommerceName>杭州马班科技有限公司</eCommerceName><eCommerceCode>341905940</eCommerceCode><declareCompanyName>杭州经济技术开发区报关有限公司</declareCompanyName><declareCompanyCode>3301280002</declareCompanyCode><declareCompanyType>个人委托第三方申报</declareCompanyType><trafMode>0</trafMode><voyageNo></voyageNo><trafName></trafName><destinationPort>1151</destinationPort><iePort>7218</iePort><ieFlag>I</ieFlag><preEntryNumber>549020151209173133</preEntryNumber><importType>1</importType></goodsDeclare><goodsDeclareDetails><goodsDeclareDetail><goodsOrder>1</goodsOrder><codeTs>01019900</codeTs><goodsItemNo>MB00007</goodsItemNo><goodsName>美国善存Centrum成人女士复合维生素多种营养素矿物质</goodsName><goodsModel>片数:100片;试用人群:女性;</goodsModel><originCountry>502</originCountry><tradeCurr>142</tradeCurr><tradeTotal>86</tradeTotal><declPrice>86.00</declPrice><declTotalPrice>86</declTotalPrice><useTo></useTo><declareCount>1</declareCount><goodsUnit>001</goodsUnit><goodsGrossWeight>400.00</goodsGrossWeight><firstUnit>001</firstUnit><firstCount>1</firstCount><secondUnit></secondUnit><secondCount></secondCount><productRecordNo></productRecordNo><webSite>http://banma.itboye.comShop/Product/detail/id/32</webSite></goodsDeclareDetail></goodsDeclareDetails></goodsDeclareModule></goodsDeclareModuleList></body></mo>';
        $content = base64_decode($content);


        $xml = simplexml_load_string($content);

        addLog("ZjportCallback/index",$xml,"","content数据转换成XML，电子口岸回调信息");
        if(empty($xml)){
            addLog("ZjportCallback/index","","XML解析失败","数据转换成XML，电子口岸回调信息");
            $this->ajaxReturn("XML解析失败!");
            exit;
        }

        $businessType = $this->getHeadBusinessType($xml);

        if(strtoupper($businessType) == 'RESULT'){
            $chkMark = "";
            $result_list = $this->getJkfResult($xml);
            $result_str = $this->getDetailInfo($result_list);

            $data = array(
                'status'=>'true',
                'info'=>NOW_TIME,
            );

            $this->ajaxReturn($data,"json");

        }elseif(strtoupper($businessType) == "PERSONAL_GOODS_DECLAR") {

            $declar = $this->getGoodsDeclar($xml);

            $data = array(
                'status'=>'true',
                'info'=>NOW_TIME,
            );

            $this->ajaxReturn($data,"json");
        }
        elseif(strtoupper($businessType) == "IMPORTBILLRESULT") {

            $this->billResult($xml);

            $data = array(
                'status'=>'true',
                'info'=>NOW_TIME,
            );

            $this->ajaxReturn($data,"json");

        }elseif(strtoupper($businessType) == "TAXISNEED") {

            $result = $this->taxIsNeed($xml);

            $data = array(
                'status'=>'true',
                'info'=>$result,
            );

            $this->ajaxReturn($data,"json");

        }else{
            addLog("ZjportCallback/index","","","无法处理的businessType",true);
        }

    }


    //私有
    //*****2.税款应征处理
    private function taxIsNeed($xml){
        $body = $xml->body;
        $jkfSign = $body->jkfSign;
        $jkfTaxIsNeedDto = (array)$body->jkfTaxIsNeedDto;

        $businessNo = strval($jkfSign->businessNo);


//        dump($jkfTaxIsNeedDto);
        $personal_no = $jkfTaxIsNeedDto['personalGoodsFormNo'];
        $tax_amount = $jkfTaxIsNeedDto['taxAmount'];
        $is_need = $jkfTaxIsNeedDto['isNeed'];

        $entity = array(
            'express_no'=>$businessNo,
            'personal_no'=>$personal_no,
            'tax_amount'=>$tax_amount,
            'is_need'=>$is_need,
            'create_time'=>time(),
        );

        $result = apiCall(OrderTaxNeedApi::ADD,array($entity));


        return $result;
    }



    //******1. 运单出区
    private function billResult($xml){

        $body = $xml->body;
        $jkfSign = $body->jkfSign;


        $businessNo = strval($jkfSign->businessNo);

        $billResultList = (array)($body->billResultList);

        foreach($billResultList as $bill){
            if(get_class($bill) == 'SimpleXMLElement'){
                $bill = (array)$bill;
                $this->addToBillResult($businessNo,$bill);
            }
        }

    }

    //******2. 运单出区
    private function addToBillResult($businessNo,$bill){
        $bill_str = $bill['wayBillNos'];
        $out_state = $bill['outState'];
        $out_time = $bill['outTime'];

        $bill_arr = explode(",",$bill_str);
        $now_time = time();
        foreach($bill_arr as $bill_no){
            $entity = array(
                'express_no'=>$bill_no,
                'out_state'=>$out_state,
                'out_time'=>$out_time,
                'create_time'=>$now_time,
                'business_no'=>$businessNo,
            );
            apiCall(OrderBillResultApi::ADD,array($entity));
        }
    }


    //个人物品申报单回执
    private function getGoodsDeclar($xml){
        $declar = new GoodsDeclar();

        $body = $xml->body;
        $jkfSign = $body->jkfSign;
        $businessNo = $jkfSign->businessNo;
        $businessNo = ((array)$businessNo);
        $businessNo = $businessNo[0];
        $goodsDeclar = $body->jkfGoodsDeclar;
        $approveResult = strval($goodsDeclar->approveResult);
        $declar->setApproveComment($goodsDeclar->approveComment);
        $declar->setApproveResult($approveResult);
        $declar->setProcessTime($goodsDeclar->processTime);
        $declar->setPersonalGoodsFormNo($goodsDeclar->personalGoodsFormNo);

        $map = array(
            'serial_no'=>$businessNo,
            'type'=>ZjportUploadHisModel::UPLOAD_GOODSD_INFO
        );
        $time = strtotime($declar->getProcessTime());

        $entity = array(
            'asyn_result'=>$declar->toString(),
            'aysn_catch_time'=>$time
        );
        $result = apiCall(ZjportUploadHisApi::SAVE,array($map,$entity));

        $result = apiCall(ZjportUploadHisApi::GET_INFO,array($map));
        addLog("ZjportCallback/index",$result,$result,"[调试] 获取ZjportUploadHis历史信息",true);
        if($result['status'] && is_array($result['info'])){
            $order_code =  $result['info']['order_code'];
            $zjport_status = strval($goodsDeclar->approveResult);
            addLog("ZjportCallback/index",$order_code,$zjport_status,"[调试] 获取订单号，电子口岸状态",true);
            $reason = $declar->getApproveComment();
            $result = apiCall(ZjportOrderStatusApi::UPDATE_STATUS,array($order_code,$zjport_status,$reason));

            $this->ajaxReturn($result,"json");
        }else{

            $this->ajaxReturn("电子口岸审批结果处理失败","json");
        }



    }


    //***result 回执
    private function getDetailInfo($jkfResult){
        $result_str = "";
        foreach($jkfResult as $vo){
            $businessNo = ((array)$vo->businessNo);
            if(is_array($businessNo) && count($businessNo) > 0){
                $businessNo = $businessNo[0];
            }
            $chkMark = $vo->chkMark;
            $noticeDate = $vo->noticeDate;
            $noticeTime = $vo->noticeTime;
            //处理失败
            $resultList = $vo->resultList;
            foreach($resultList as $detail){
                $result_str .= $detail->jkfResultDetail->resultInfo;
            }
            if($chkMark == 2){
                $chkMark = "处理失败!";
            }else{
                $chkMark = "处理成功!";
            }
            $order_code = $this->getOrderCodeBy($businessNo);
            $this->addToHistory($order_code,$businessNo,$chkMark,$result_str,strtotime($noticeDate.$noticeTime));
        }
        return $result_str;
    }

    private function getJkfResult($xml){
        $list = (array)$xml->body->list;

        return $list;
    }


    private function getHeadBusinessType($xml){

        $businessType = (array)$xml->head->businessType;

        return $businessType[0];
    }

    private function getOrderCodeBy($business_no){
        $result = apiCall(ZjportUploadHisApi::GET_INFO,array(array('serial_no'=>$business_no)));

        if($result['status'] && is_array($result['info'])){
            return $result['info']['order_code'];
        }

        return "unknown";

    }

    private function  addToHistory($order_code,$serial_no,$upload_content,$result,$notice_time){
        if(empty($order_code)){
            $order_code = "";
        }


        if(empty($upload_content)){
            $upload_content = "";
        }

        if(empty($result)){
            $result = "";
        }

        if(is_array($upload_content)){
            $upload_content = json_encode($upload_content);
        }

        if(is_array($result)){
            $result = json_encode($result);
        }

        $entity = array(
            'order_code'=>$order_code,
            'upload_time'=>$notice_time,
            'serial_no'=>$serial_no,
            'result'=>$result,
            'asyn_result'=>'',
            'upload_content'=>$upload_content,
            'type'=> ZjportUploadHisModel::UPLOAD_CALLBACK_RESULT, //电子口岸回执
        );

        $result = apiCall(ZjportUploadHisApi::ADD,array($entity));

    }



}